package com.flight.model.dao.impl;

import com.flight.model.dao.CabinDAO;
import com.flight.model.entity.Cabin;
import com.flight.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 舱位DAO实现类
 */
public class CabinDAOImpl implements CabinDAO {
    @Override
    public List<Cabin> getByFlightNo(String flightNo) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<Cabin> cabins = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM cabin WHERE flight_no = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, flightNo);
            rs = stmt.executeQuery();

            while (rs.next()) {
                Cabin cabin = new Cabin();
                cabin.setCabinId(rs.getInt("cabin_id"));
                cabin.setFlightNo(flightNo);
                cabin.setCabinType(rs.getString("cabin_type"));
                cabin.setCabinPrice(rs.getDouble("cabin_price"));
                cabin.setTotalSeats(rs.getInt("total_seats"));
                cabin.setRemainingSeats(rs.getInt("remaining_seats"));
                cabins.add(cabin);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }
        return cabins;
    }

    @Override
    public boolean reduceRemainingSeats(Integer cabinId) {
        // 扣减余票（剩余座位需 >= 1）
        return updateRemainingSeats(cabinId, -1);
    }

    @Override
    public boolean increaseRemainingSeats(Integer cabinId) {
        // 增加余票（退票时）
        return updateRemainingSeats(cabinId, 1);
    }

    // 通用更新余票方法
    private boolean updateRemainingSeats(Integer cabinId, int num) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE cabin SET remaining_seats = remaining_seats + ? WHERE cabin_id = ? AND remaining_seats + ? >= 0";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, num);
            stmt.setInt(2, cabinId);
            stmt.setInt(3, num); // 避免扣减后出现负数
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.close(conn, stmt, null);
        }
    }
}